package com.javasoft.controller.YZX;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.javasoft.entity.YZX.ClassResults;
import com.javasoft.service.YZX._interface.ClassResultsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Field;
import java.util.*;

@RestController
@RequestMapping("class-results")
@Slf4j
public class ClassResultsController {

    @Autowired
    private ClassResultsService classResultsService;

    /**
     * 计算并存储班级成绩统计信息（使用POST方法）
     *
     * @return 成功与否的状态码
     */
    @PostMapping("/calculate")
    public ResponseEntity<Void> calculateAndStoreClassResults() {
        try {
            classResultsService.calculateAndStoreClassResults();
            return ResponseEntity.status(HttpStatus.CREATED).build();
        } catch (Exception e) {
            log.error("Error during calculating and storing class results: {}", e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }



    /**
     * 获取班级成绩统计信息（使用GET方法），并将题目正确率转换为百分比格式
     *
     * @param className 班级名称
     * @param examId 考试ID
     * @return 包含班级成绩统计信息的响应实体
     */
    @GetMapping("/{className}/{examId}")
    public ResponseEntity<Map<String, Object>> getClassResults(@PathVariable String className, @PathVariable Long examId) {
        try {
            LambdaQueryWrapper<ClassResults> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ClassResults::getClassName, className)
                    .eq(ClassResults::getExamId, examId);

            // 使用 one 方法从 service 中获取单个结果
            ClassResults result = ((IService<ClassResults>) classResultsService).getBaseMapper().selectOne(queryWrapper);
            if (result == null) {
                return ResponseEntity.notFound().build();
            }

            // 构建一个Map来保存格式化的结果
            Map<String, Object> formattedResult = new HashMap<>();
            formattedResult.put("className", result.getClassName());
            formattedResult.put("examId", result.getExamId());
            formattedResult.put("average", result.getAverage());

            List<String> questionRates = new ArrayList<>(30);
            for (int i = 1; i <= 30; i++) {
                try {
                    Field field = ClassResults.class.getDeclaredField("que" + i);
                    field.setAccessible(true);
                    Double rate = (Double) field.get(result);
                    // 将原始值转换为百分比，并保留两位小数
                    questionRates.add(Optional.ofNullable(rate)
                            .map(value -> String.format("%.2f%%", value * 100))
                            .orElse("N/A"));
                } catch (NoSuchFieldException | IllegalAccessException e) {
                    questionRates.add("N/A");
                    log.error("Error converting question rates: {}", e.getMessage(), e);
                }
            }

            formattedResult.put("questionRates", questionRates);

            return ResponseEntity.ok(formattedResult);
        } catch (Exception e) {
            log.error("Error retrieving class results for class: {} and examId: {}: {}", className, examId, e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }






}